package com.wu.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.wu.pojo.po.paperPo.Answer;
import com.wu.pojo.po.paperPo.Counter;
import com.wu.pojo.res.Result;
import com.wu.pojo.dto.PaperAnswerDTO;
import com.wu.service.AnswerService;
import com.wu.service.QuestionService;
import com.wu.utils.CommonUtils;
import com.wu.utils.JwtUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * [答题接口功能]
 *
 * @Author : [wuzhengru]
 * @Version : [v1.0]
 * @Date : [2021/5/08 17:31]
 */
@Slf4j
@RestController
@RequestMapping("/api/v1/admin/ques")
@Api(tags = "答题接口", description = "QuestionController")
public class QuestionController {

    @Reference
    private AnswerService answerService;
    @Reference
    private QuestionService questionService;

    /**
     * 填写问卷
     */
    @RequiresRoles("user")
    @ApiOperation("用户上传问卷填写答案")
    @PostMapping("quesAnswer")
    public Result insertAnswer(@Valid @RequestBody PaperAnswerDTO paperAnswerDTO, BindingResult result) {

        // 1、参数校验
        Result res = Commonts.getErrors(result);
        if (!(null == res || "".equals(res))) {// return校验错误
            return Commonts.getErrors(result);
        }

        // 2、验证重复性
        String userId = null;// 拿到userInfo
        try {
            userId = (String)JwtUtils.getClaimByToken(paperAnswerDTO.getUserInfo()).get("userId");
        } catch (Exception e) {
            log.error("token解析失败！",e);
            return Result.fail("token解析失败！");
        }
        // 查询
        if (null != answerService.queryAnswerByPaperIdAndUserId(paperAnswerDTO.getPaperId(), userId)
                && answerService.queryAnswerByPaperIdAndUserId(paperAnswerDTO.getPaperId(), userId).size() > 0) {
            log.info("您已答过题了，请勿重复提交！");
            return Result.fail("您已答过题了，请勿重复提交！");
        }

        // 3、参数初始化
        List<Answer> answerList = paperAnswerDTO.answerListInit();// 初始化答案列表
        for (Answer answer : answerList) { // 校验作答题目
            String answerContents = answer.getAnswerContents();
            if (answerContents.length() < 3 || answerContents.equals("[\"[]\"]")) { // 简单题未填时会传入字符串
                return Result.fail(String.format("第%d题未作答，请完成全部题目再进行提交",questionService.queryQuestionById(answer.getQuestionId()).getQuestionNo()));
            }
        }

        Counter counter = new Counter(); // 答案入库时计算本此调查指标
        counter.setId(CommonUtils.getUUID()).setPaperId(paperAnswerDTO.getPaperId())
                .setUserId(paperAnswerDTO.getUserId());

        // 4、入库
        answerService.insertAnswerAndCounter(answerList,counter);

        return Result.succ("问卷填写成功");
    }


}
